package cnki.proxy;

import cnki.db.mongo.MongoDao;
import com.mongodb.DBObject;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.Random;

import static com.han.http.util.Print.printlnErr;

/**
 * @author: Han
 * @date: 2018/9/21 9:36
 * @dscription: TODO
 */
public class ProxyImpl {
    /**
     * 代理IP地址
     */
    private String ip;
    /**
     * 代理端口
     */
    private int port;

    /**
     * 获取代理的ip和port
     */
    public ProxyImpl() {
    }

    /**
     * 获取类型为HTTP的代理
     *
     * @return HTTPProxy
     */
    public java.net.Proxy getHttpProxy() {
        getProxyAddress();
        SocketAddress socketAddress = new InetSocketAddress(ip, port);
        try {
            Thread.sleep(1000 * 2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return new java.net.Proxy(java.net.Proxy.Type.HTTP, socketAddress);
    }

    /**
     * 从指定库中去除代理ip和端口
     */
    private void getProxyAddress() {

        Random random = new Random();
        //获取HttpHost,如果获取失败,重复指定次数,超过则退出程序
        int maxRepeatCount = 10;
        int repeatCount = 0;
        while (repeatCount++ <= maxRepeatCount) {
            try {
                //随机查找记录
                int flagInt = random.nextInt(6) + 1;
                String[] keys = {"flag"};
                Object[] values = {flagInt};
                DBObject dbObject = MongoDao.getMongoDaoInstance().find("siteHost", "proxy", 1, keys, values).get(0);
                ip = (String) dbObject.get("ip");
                port = (Integer) dbObject.get("port");
                break;
            } catch (Exception e) {
                //如果失败,等待3秒重试
                try {
                    Thread.sleep(1000 * 3);
                } catch (InterruptedException ee) {
                    ee.printStackTrace();
                }
                printlnErr("获取代理ip失败,重试第" + repeatCount + "次");
            }
        }
    }
}
